/*
 * www.unisinsight.com Inc.
 * Copyright (c) 2019 All Rights Reserved.
 */
package com.fengwuj.mutils.image;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 修订记录：
 * jiangbo 2020/4/26 15:50 创建
 *
 * @author jiangbo
 */
@Slf4j
public class Base64Utils {

    private static final Long MILLS_PER_SECONDS = 1000L;
    private static final int TIMEOUT_SECONDS = 5;
    private static final String BASE64_PREFIX = "data:image/jpeg;base64,";
    private static final int BYTES_PER_READ = 1024;
    /**
     * 文件地址转Base64
     * @param localImageFilePath
     * @return
     */
    public static String localImageToBase64WithoutHeaderInfo(String localImageFilePath){
        if (StringUtils.isBlank(localImageFilePath)){
            log.info("文件地址为空");
            return null;
        }
        String base64Str = null;
        try {
            //通过输入流获取图片数据
            InputStream inStream = new FileInputStream(localImageFilePath);
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[BYTES_PER_READ];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            //关闭输入流
            inStream.close();
            byte[] data = outStream.toByteArray();
            //对字节数组Base64编码
            Base64 encoder = new Base64();
            //返回Base64编码过的字节数组字符串
            base64Str = encoder.encodeBase64String(data);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return base64Str;
    }

    public static String localImageToBase64WithHeaderInfo(String imageFilePath){
        return BASE64_PREFIX + localImageToBase64WithoutHeaderInfo(imageFilePath);
    }

    /**
     * 将网络图片编码为base64
     *
     * @param imageUrl
     * @return
     */
    public static String netImageToBase64WithoutHeaderInfo(String imageUrl) {
        String base64Str = null;
        try {
            String filename = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
            filename = URLEncoder.encode(filename, "UTF-8");
            imageUrl = imageUrl.substring(0, imageUrl.lastIndexOf('/') + 1) + filename;
            URL url = new URL(imageUrl);
            //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
            log.info("图片的路径为:{}", url.toString());
            //打开链接
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            conn.setConnectTimeout(TIMEOUT_SECONDS * MILLS_PER_SECONDS.intValue());
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[BYTES_PER_READ];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            //关闭输入流
            inStream.close();
            byte[] data = outStream.toByteArray();
            //对字节数组Base64编码
            Base64 encoder = new Base64();
            //返回Base64编码过的字节数组字符串
            base64Str = encoder.encodeBase64String(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return base64Str;
    }

    public static String netImageToBase64WithHeaderInfo(String imageUrl){
        return BASE64_PREFIX + netImageToBase64WithoutHeaderInfo(imageUrl);
    }
}
